package com.eurobcoin.helper;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerHelper {

	public static void processTemplate(
			Configuration config, 
			String template, @SuppressWarnings("rawtypes") Map data, 
			HttpServletResponse response) throws IOException, TemplateException {
		
		Template tpl = config.getTemplate(template);
		
		StringWriter sw = new StringWriter();
		
		tpl.process(data, sw);
		
		String out = sw.toString();
		
		response.setContentType("application/xhtml+xml");
		response.setCharacterEncoding("UTF-8");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println(out);
		response.getWriter().flush();
	}
	
	public static Configuration buildConfiguration(String basePath) {
		Configuration freemarkerConfig = new Configuration();
		
		ClassTemplateLoader ctl = new ClassTemplateLoader(FreemarkerHelper.class, basePath);
		
		freemarkerConfig.setTemplateLoader(ctl);
		
		return freemarkerConfig;
	}
	
}
